package com.liukaixin.product.ru.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.notice.NoticesActivity;
import com.liukaixin.product.ru.data.model.Notice;
import com.liukaixin.product.ru.data.model.Result;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.ApplyStatusEnum;
import com.liukaixin.product.ru.enumerate.NoticeTypeEnum;
import com.liukaixin.product.ru.enumerate.ResultTypeEnum;
import com.liukaixin.product.ru.util.CheckUtil;
import com.orhanobut.logger.Logger;

import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PollingService extends Service {
    public static final String ACTION = "com.liukaixin.product.ru.service.PollingService";

    private Notification notification;
    private NotificationManager notificationManager;
    private NoticeService noticeService = ServiceFactory
            .createRetrofitService(NoticeService.class,
                    ServiceFactory.BASE_URL);
    private User user = CheckUtil.isLogin();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        buildNotification();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        new PollingThread().start();
    }

//    //初始化通知栏配置
//    private void initNotifiManager() {
//        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        int icon = R.drawable.logo;
//        mNotification = new Notification();
//        mNotification.icon = icon;
//        mNotification.tickerText = "New Message";
//        mNotification.defaults |= Notification.DEFAULT_SOUND;
//        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
//    }
//
//    //弹出Notification
//    private void showNotification() {
//        mNotification.when = System.currentTimeMillis();
//        //Navigator to the new activity when click the notification title
//        if (CheckUtil.isLogin() != null) {
//
//            Intent i = new Intent(this, NoticesActivity.class);
//            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
//                    Intent.FLAG_ACTIVITY_NEW_TASK);
//            mNotification.setLatestEventInfo(this,
//                    getResources().getString(R.string.app_name),
//                    "You have new message!", pendingIntent);
//            mManager.notify(0, mNotification);
//        }
//    }

    private void buildNotification() {
        Logger.i("buildNotification");
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(PollingService.this);
        builder1.setSmallIcon(R.drawable.logo); //设置图标
        builder1.setTicker("显示通知");
        builder1.setContentTitle("您有未审核的团队申请"); //设置标题
        builder1.setContentText("点击查看详细内容"); //消息内容
        builder1.setWhen(System.currentTimeMillis()); //发送时间
        builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音，振动方式，灯光
        builder1.setAutoCancel(true);//打开程序后图标消失
        if (CheckUtil.isLogin() != null) {
            Intent intent = new Intent(PollingService.this, NoticesActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(PollingService.this, 0,
                    intent, 0);
            builder1.setContentIntent(pendingIntent);
        }
        notification = builder1.build();
    }

    /**
     * Polling thread
     * 模拟向Server轮询的异步线程
     *
     * @Author Ryan
     * @Create 2013-7-13 上午10:18:34
     */

    class PollingThread extends Thread {
        @Override
        public void run() {
            if (user != null) {
                Logger.i("new polling message");
                noticeService.getNoticesByUserId(1, 10,
                        NoticeTypeEnum.TEAM_NOTICE.getTypeCode(), user.getId())
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Result<List<Notice>>>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e(e, e.getMessage());
                            }

                            @Override
                            public void onNext(Result<List<Notice>> result) {
                                if (result.getCode().equals(ResultTypeEnum.SUCCESS.getValue())) {
                                    for (Notice notice : result.getBean()) {
                                        if (notice.getRead().equals(
                                                ApplyStatusEnum.NOT_CHECK.getTypeCode())) {
                                            // 通过通知管理器发送通知
                                            notificationManager.notify(124, notification);
                                            break;
                                        }
                                    }
                                }
                            }
                        });
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}